<?php

namespace app\manystore\model;

use think\Model;
use think\Db;
use think\Page;
use \app\manystore\model\Goods as GoodsModel;


class Order extends Model
{
    // 表名
    protected $name = 'order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;
    /* @var string $error 錯誤信息 */
    public $error = '';

    // 追加属性
    protected $append = [
        'order_attributes_text',
        'order_type_text',
        'pay_status_text',
        'paytime_text',
        'freight_status_text',
        'freighttime_text',
        'receipt_status_text',
        'receipttime_text',
        'order_status_text',
        'refund_status_text',
        'comment_status_text',
        'region_type_text'
    ];
    

    
    public function getOrderAttributesList()
    {
        return ['10' => __('Order_attributes 10'), '20' => __('Order_attributes 20')];
    }

    public function getOrderTypeList()
    {
        return ['10' => __('Order_type 10'), '20' => __('Order_type 20')];
    }

    public function getPayStatusList()
    {
        return ['10' => __('Pay_status 10'), '20' => __('Pay_status 20')];
    }

    public function getFreightStatusList()
    {
        return ['10' => __('Freight_status 10'), '20' => __('Freight_status 20')];
    }

    public function getReceiptStatusList()
    {
        return ['10' => __('Receipt_status 10'), '20' => __('Receipt_status 20')];
    }

    public function getOrderStatusList()
    {
        return ['10' => __('Order_status 10'), '20' => __('Order_status 20'), '30' => __('Order_status 30')];
    }

    public function getRefundStatusList()
    {
        return ['10' => __('Refund_status 10'), '20' => __('Refund_status 20'), '30' => __('Refund_status 30'), '40' => __('Refund_status 40')];
    }

    public function getCommentStatusList()
    {
        return ['10' => __('Comment_status 10'), '20' => __('Comment_status 20')];
    }

    public function getRegionTypeList()
    {
        return ['1' => __('Region_type 1'), '2' => __('Region_type 2')];
    }


    public function getOrderAttributesTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_attributes']) ? $data['order_attributes'] : '');
        $list = $this->getOrderAttributesList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getOrderTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_type']) ? $data['order_type'] : '');
        $list = $this->getOrderTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getFreightStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['freight_status']) ? $data['freight_status'] : '');
        $list = $this->getFreightStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getFreighttimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['freighttime']) ? $data['freighttime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getReceiptStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['receipt_status']) ? $data['receipt_status'] : '');
        $list = $this->getReceiptStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getReceipttimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['receipttime']) ? $data['receipttime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOrderStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_status']) ? $data['order_status'] : '');
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getRefundStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['refund_status']) ? $data['refund_status'] : '');
        $list = $this->getRefundStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCommentStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['comment_status']) ? $data['comment_status'] : '');
        $list = $this->getCommentStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getRegionTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['region_type']) ? $data['region_type'] : '');
        $list = $this->getRegionTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setFreighttimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setReceipttimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * [order_add 下訂單]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-17T01:58:31+0800
     * @param      [type]                   $user_id      [用戶ID]
     * @param      [type]                   $order        [訂單信息]
     * @param      [type]                   $address_info [用戶地址]
     * @param      [type]                   $order_type   [訂單類型:10=商城訂單,20=積分訂單]
     * @return     [type]                                 [description]
     */
    public function order_add($user_id,$order,$address_info,$order_type = 10){
        $time = time();
        Db::startTrans();
        try {
            $parent_order_no = orderNo('5');
            $shop_count = count($order['goods_list']);
            foreach ($order['goods_list'] as $key => $value) {
                // 循環店鋪
                $order_insert = [];
                $order_insert['order_no'] = $shop_count == 1 ? $parent_order_no : orderNo('5');
                $order_insert['parent_order_no'] = $parent_order_no;
                $order_insert['shop_id'] = $value['shop_id'];
                $order_insert['user_id'] = $user_id;
                $order_insert['order_attributes'] =  $shop_count == 1 ? '10' : '20';
                $order_insert['order_type'] =  $order_type;
                $order_insert['total_price'] = $value['shopTotalPrice'];
                $order_insert['total_integral'] = $value['shopTotalIntegral'];
                $order_insert['delivery_price'] = $value['shopTotalDeliveryPrice'];
                $order_insert['pay_price'] = $value['orderPayPrice'];
                // 積分訂單跳過付款這一步驟
                if ( $order_type == 20 ) {
                    $order_insert['paytime'] = $time;
                    $order_insert['pay_status'] = '20';
                    $order_insert['order_status'] = '20';
                }
                $order_insert['name'] = $address_info['name'];
                $order_insert['mobile'] = $address_info['mobile'];
                $order_insert['address'] = $address_info['address'];
                $order_insert['region_type'] = $address_info['region_type'];
                $order_insert['createtime'] = $time;
                $order_id = self::insertGetId($order_insert);
                if ( !$order_id ) {
                    $this->setError('操作失敗');
                    Db::rollback();
                    return ['status'=>false,'data'=>[]];
                }

                $goodsList = [];
                // 循環店鋪內商品
                foreach ($value['goods_list'] as $k => $goods) {
                    $goodsList[] = [
                        'order_id'=> $order_id,
                        'goods_id' => $goods['goods_id'],
                        'goods_name' => $goods['goods_name'],
                        'images' => $goods['images'],
                        'spec_type' => $goods['spec_type'],
                        'spec_sku_id' => $goods['goods_sku']['spec_sku_id'],
                        'goods_spec_id' => $goods['goods_sku']['goods_spec_id'],
                        'goods_attr' => $goods['goods_sku']['goods_attr'],
                        'content' => $goods['content'],
                        'goods_no' => $goods['goods_sku']['goods_no'],
                        'goods_price' => $goods['goods_sku']['goods_price'],
                        'line_price' => $goods['goods_sku']['line_price'],
                        'integral' => $goods['goods_sku']['integral'],
                        'total_integral' => $goods['total_integral'],
                        'total_num' => $goods['total_num'],
                        'total_price' => $goods['total_price'],
                        'delivery_price' => $goods['delivery_price'],
                        'createtime' => $time,
                        'goods_type' => $order_type == 10 ? 0 : 1
                    ];
                }

                $status = db('order_goods')->insertAll($goodsList);
                if ( !$status ) {
                    $this->setError('操作失敗');
                    Db::rollback();
                    return ['status'=>false,'data'=>[]];
                }
                // 積分商品抵扣積分
                if ( $order_type == 20 ) {
                    $status = addPoints($user_id,-$order['orderTotalIntegral'],'兌換商品','4',$parent_order_no,$time);
                    if ( !$status ) {
                        Db::rollback();
                        $this->error('操作失敗');
                    }
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->setError($e->getMessage());
            return ['status'=>false,'data'=>[]];
        }
        return ['status'=>true,'data'=>['parent_order_no'=>$parent_order_no]];
    }

    /**
     * [getBuyNow 立即購買]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-17T02:24:38+0800
     * @param      [type]                   $user_id      [description]
     * @param      [type]                   $goods_id     [description]
     * @param      [type]                   $goods_num    [description]
     * @param      [type]                   $goods_sku_id [description]
     * @return     [type]                                 [description]
     */
    public function getBuyNow($user_id, $goods_id, $goods_num, $goods_sku_id)
    {
        $gmodel = new GoodsModel;
        // 商品信息
        $goods = $gmodel->detail($goods_id);
        $goods['show_error'] = 0;
        // 判断商品是否下架
        if ($goods['goods_status'] !== '10') {
            $goods['show_error'] = 1;
            $goods['show_error_text'] = '已下架';
            $this->setError('很抱歉，商品 [' . $goods['goods_name'] . $goods['goods_sku']['goods_attr'] . '] 不存在或已下架');
        }
        // 商品sku信息
        $goods['goods_sku'] = $goods->getGoodsSku($goods_sku_id);
        // 判断商品库存
        if ($goods_num > $goods['goods_sku']['stock_num']) {
            $goods['show_error'] = 2;
            $goods['show_error_text'] = '库存不足';
            $this->setError('很抱歉，商品 [' . $goods['goods_name'] . $goods['goods_sku']['goods_attr'] . '] 庫存不足');
        }

        // 商品单价
        $goods['goods_price'] = $goods['goods_sku']['goods_price'];
        // 商品总价
        $goods['total_num'] = $goods_num;
        $goods['total_price'] = $totalPrice = bcmul($goods['goods_price'], $goods_num, 2);
        $goods['total_integral']= bcmul($goods['goods_sku']['integral'], $goods_num, 2);
        $order_pay_price = bcadd($totalPrice, $goods['delivery_price'], 2);

        $shop = db('manystore_shop')
                ->where(['id'=>$goods['shop_id']])
                ->find();

        $shopList = [];
        $shopList[] = ['shop_id'=>$shop['id'],'logo'=>$shop['logo'],'name'=>$shop['name'],'shopTotalPrice'=>$goods['total_price'],'shopTotalIntegral'=>$goods['total_integral'],'shopTotalDeliveryPrice'=>$goods['delivery_price'],'orderPayPrice'=>$order_pay_price,'goods_list'=>[$goods]];

        return [
            'goods_list' => $shopList,               // 商品详情
            'order_total_num' => $goods_num,        // 商品总数量
            'order_total_price' => $totalPrice,    // 商品总金额 (不含运费)
            'order_pay_price' => bcadd($totalPrice, $goods['delivery_price'], 2),  // 实际支付金额(包含運費)
            'orderTotalIntegral' => $goods['total_integral'],
            'has_error' => $this->hasError(),
            'error_msg' => $this->getError(),
        ];
    }

    private function setError($error)
    {
        empty($this->error) && $this->error = $error;
    }

    /**
     * 獲取錯誤信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    public function hasError()
    {
        return !empty($this->error);
    }
    
    /*
    *獲取訂單列表
    */
    public function getOrderList($where,$field='*',$order='o.id desc')
    {
        $total = self::alias('o')
            ->where($where)
            ->join('manystore_shop s','s.id = o.shop_id','left')
            ->count();

        $page = new Page($total,10);

        $list = self::alias('o')
            ->field($field)
            ->join('manystore_shop s','s.id = o.shop_id','left')
            ->where($where)
            ->limit($page->firstRow.','.$page->listRows)
            ->order($order)
            ->select();

        foreach ($list as $key => &$value) {
            $order_goods = db('order_goods')
                        ->field('id as order_goods_id,goods_id,goods_name,images,goods_attr,goods_price,total_price,integral,total_integral,total_num')
                        ->where(['order_id'=>$value['id']])
                        ->select();
            foreach ($order_goods as $k => &$v) {
                $v['images'] = explode(',', $v['images'])[0];
            }
            unset($v);

            $value['order_goods'] = $order_goods;

        }
        unset($value);

        return ['total'=>$total,'listrows'=>$page->listRows,'totalpages'=>$page->totalPages,'data'=>$list];
    }

    public function getOrderInfo($where,$field='*',$order='o.id desc')
    {
        $info = self::alias('o')
            ->field($field)
            ->join('manystore_shop s','s.id = o.shop_id','left')
            ->where($where)
            ->find();

        if ( !$info ) {
            return [];
        }

        $order_goods = db('order_goods')
                    ->field('id as order_goods_id,goods_id,goods_name,images,goods_attr,goods_price,total_price,integral,total_integral,total_num')
                    ->where(['order_id'=>$info['id']])
                    ->select();

        // 退款情況
        $refund = [];
        if ( $info['refund_status'] != '10' ) {
            $refund = db('order_refund')
            ->field('id,refund_reason,refund_content,return_reason,createtime')
            ->where(['order_id'=>$info['id']])
            ->order('id desc')
            ->find();
        }
        if ( $refund ) {
            $images = db('upload_images')
                            ->where(['type'=>'5','relation_id'=>$refund['id']])
                            ->column('images');
            $refund['images'] = $images;
            unset($refund['id']);
        }

        $info['refund'] = $refund;
        
        foreach ($order_goods as $k => &$v) {
            $v['images'] = explode(',', $v['images'])[0];
        }
        unset($v);

        $info['order_goods'] = $order_goods;

        return $info;
    }

}
